import { addCommunicateApi, editCommunicateApi, getUserCommunicateApi } from '@/services/user';
import useTableList from '@/utils/useTableList';
import {
  Button,
  Col,
  DatePicker,
  Flex,
  Form,
  Input,
  Modal,
  ModalProps,
  Row,
  Space,
  Table,
} from 'antd';
import React, { useEffect } from 'react';
import styles from './index.less';
import {
  EditOutlined,
  PlusCircleOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import useEditModal from '@/utils/useEditModal';

interface CommunicateModalProps extends ModalProps {
  item?: any;
  onClose?: () => void;
}

const CommunicateModal: React.FC<CommunicateModalProps> = ({ item, onClose, ...props }) => {
  const { loading, page, pageSize, total, onFinish, onPageChange, form, datasource } = useTableList(
    {
      fetchApi: getUserCommunicateApi,
      immediate: false,
    },
  );

  const {
    loading: editLoading,
    form: editForm,
    currentData,
    setCurrentData,
    onOk,
    onCancel,
  } = useEditModal({
    editApi: editCommunicateApi,
    addApi: addCommunicateApi,
    successCb: () => {
      onPageChange(page);
    },
  });

  const columns: ColumnsType<any> = [
    {
      title: '记录ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 200,
    },
    {
      title: '用户姓名',
      dataIndex: 'userName',
      key: 'userName',
      width: 200,
    },
    {
      title: '用户手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 200,
    },
    {
      title: '沟通内容',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
    },
    {
      title: '沟通人ID/创建人ID',
      dataIndex: 'creatorId',
      key: 'creatorId',
      width: 200,
    },
    {
      title: '沟通人姓名/创建人姓名',
      dataIndex: 'creatorName',
      key: 'creatorName',
      width: 200,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 100,
      align: 'center',
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              variant="outlined"
              onClick={() => {
                setCurrentData({
                  id: row.id,
                  userId: item?.id,
                  remark: row.remark,
                });
              }}
              icon={<EditOutlined />}
            >
              编辑
            </Button>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    if (item?.id) {
      form.resetFields();
      onFinish({
        userId: item.id,
      });
    }
  }, [item]);

  return (
    <Modal
      width={'calc(100vw - 200px)'}
      centered
      title="沟通记录管理"
      {...props}
      destroyOnHidden
      maskClosable={false}
      onCancel={onClose}
      footer={(_, Bnts) => (
        <Flex align="center" justify="center" gap={15}>
          <Bnts.CancelBtn />
        </Flex>
      )}
    >
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form
            form={form}
            onFinish={(v: any) => {
              const query: any = {
                userId: item.id,
              };
              if (v.time) {
                query.createTimeStart = dayjs(v.time[0]).format('YYYY-MM-DD 00:00:00');
                query.createTimeEnd = dayjs(v.time[1]).format('YYYY-MM-DD 23:59:59');
              }
              onFinish(query);
            }}
            onReset={() => onFinish({})}
            labelCol={{
              span: 5,
            }}
            style={{ width: '100%' }}
          >
            <Row gutter={[20, 20]}>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={8}>
                <Form.Item label="沟通时间" name="time">
                  <DatePicker.RangePicker allowClear placeholder={['开始时间', '结束时间']} />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={16} xxl={16}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button htmlType="reset" icon={<ReloadOutlined />}>
                    重置
                  </Button>
                  <Button
                    type="primary"
                    icon={<PlusCircleOutlined />}
                    onClick={() => {
                      setCurrentData({
                        userId: item?.id,
                      });
                    }}
                  >
                    新增记录
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            columns={columns}
            dataSource={datasource}
            loading={loading}
            rowKey="id"
            scroll={{ x: 1800 }}
            locale={{ emptyText: '暂无沟通记录' }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false,
              showQuickJumper: true,
              onChange: onPageChange,
              showTotal: (total) => `共 ${total} 条数据`,
            }}
          />
        </div>
      </Row>
      <Modal
        title={currentData?.id ? '编辑记录' : '新增记录'}
        open={!!currentData}
        onCancel={onCancel}
        onOk={onOk}
        width={800}
        maskClosable={false}
        centered
        okButtonProps={{ loading: editLoading }}
      >
        <Form
          form={editForm}
          style={{
            padding: '20px 0',
          }}
          labelCol={{ span: 4 }}
          wrapperCol={{
            span: 18,
          }}
        >
          <Form.Item name="id" hidden></Form.Item>
          <Form.Item name="userId" hidden></Form.Item>
          <Form.Item
            label="沟通内容"
            name="remark"
            rules={[{ required: true, message: '请输入沟通内容', whitespace: true }]}
          >
            <Input.TextArea rows={4} placeholder="请输入沟通内容" showCount maxLength={200} />
          </Form.Item>
        </Form>
      </Modal>
    </Modal>
  );
};

export default CommunicateModal;
